package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.config.AliPay;
import cn.itsource.ymcc.constant.OrderStatusConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderDelayCloseConsumer",
        topic = OrderStatusConstants.TOPIC_COURSE_ORDER_DELAY_CLOSE,
        selectorExpression = OrderStatusConstants.TAGS_COURSE_ORDER_DELAY_CLOSE
)
@Slf4j
public class OrderDelayCloseConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private AliPay aliPay;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String orderNo = new String(body, "utf-8");
            PayOrder payOrder = payOrderMapper.selectOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
            if(OrderStatusConstants.ORDER_DEFAULT.equals(payOrder.getPayStatus())){
                //进行关单  修改自己的状态
                payOrder.setPayStatus(OrderStatusConstants.ORDER_OUT_TIME);
                payOrderMapper.updateById(payOrder);
                //告诉支付宝 关单
                aliPay.close(payOrder.getOrderNo());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
